package com.dongdongshop.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.dongdongshop.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("file")
@Slf4j
public class FileController {

    @PostMapping("upload")
    public Result upload(@RequestParam("image")MultipartFile image){
        log.info("进入上传方法,上传的文件名字:{}",image.getOriginalFilename());
        String http = "https://";
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t9YXCwP65czcQr6fkNX";
        String accessKeySecret = "dLOTi1gKBuNQ2OG2ojJmsIEr7b0DkV";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "dk-2208-cyr";
        String fileName = image.getOriginalFilename();
        String newName = UUID.randomUUID().toString()+fileName.substring(fileName.indexOf("."));
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "image/"+newName;
        log.info("图片名字为:{}",objectName);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            ossClient.putObject(bucketName, objectName, image.getInputStream());
        } catch (OSSException | IOException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //https://dk-2208-cyr.oss-cn-beijing.aliyuncs.com/image/dc5e41cb-fecf-4490-a78c-9c2947d88c84.jpg
        StringBuffer buffer = new StringBuffer();
        buffer.append(http).append(bucketName).append(".").append(endpoint).append("/").append(objectName);
        return Result.OK().setData(buffer.toString());
    }
}
